#include "MainWindow.h"
#include "PluginInfoWidget.h"
#include "ui_MainWindow.h"

#include <QFile>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("插件运行监控");
    resize(1200,800);

    ui->_pluginMsg->setReadOnly(true);
    ui->_pluginMsg->setContextMenuPolicy(Qt::NoContextMenu);
    ui->_pluginMsg->setStyleSheet("background-color: rgb(255, 255, 255);border:none;font: 12pt \"Microsoft YaHei\"");
    ui->_pluginMsg->document()->setMaximumBlockCount(100);

    ui->logTab->hide();
    ui->tabWidget->tabBar()->hide();

    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->setSelectionMode(QAbstractItemView::NoSelection);
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget->setColumnHidden(0,true);
}

MainWindow::~MainWindow()
{
    //_udpClient->abortNetword();
    _udpThread->requestInterruption();
    _udpThread->quit();
    _udpThread->wait();
    _udpThread->deleteLater();
    _udpClient->deleteLater();

    delete ui;
}

void MainWindow::initNetwork()
{
    QString ip = "127.0.0.1";
    int port = 9215;
    QFile file("../ipConfig.json");
    if(file.exists() && file.open(QIODevice::ReadOnly)){
        auto byteArr = file.readAll();
        parseConfigFile(byteArr,ip,port);
        file.close();
    }

    _udpClient = new UdpClient;
    _udpClient->bindNetwork(ip,port);
    _udpThread = new QThread;
    _udpClient->moveToThread(_udpThread);
    _udpThread->start();

    connect(_udpClient,&UdpClient::sendMessage,this,[=](const QString& msg){
        ui->_pluginMsg->append(msg);
    },Qt::QueuedConnection);

    connect(_udpClient,&UdpClient::sendPluginData,
            this,&MainWindow::recvPluginData,Qt::QueuedConnection);
}

void MainWindow::parseConfigFile(const QByteArray& array, QString& ip, int& port)
{
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(array,&parseError);
    if(doc.isNull() || parseError.error != QJsonParseError::NoError){
        return;
    }

    do{
        if(!doc.isObject()){
            break;
        }

        auto objRoot = doc.object();
        if(!objRoot.contains("pluginNetWork")){
            break;
        }

        auto pluginNetWork = objRoot.value("pluginNetWork");
        if(!pluginNetWork.isObject()){
            break;
        }

        auto pluginNetWorkRoot = pluginNetWork.toObject();
        if(pluginNetWorkRoot.contains("ip")){
            ip = pluginNetWorkRoot.value("ip").toString();
        }
        if(pluginNetWorkRoot.contains("port")){
            port = pluginNetWorkRoot.value("port").toInt();
        }
    }while(false);
}

void MainWindow::recvPluginData(PluginCommand command, const QString& pluginName, const QVariant& variant)
{
    auto table = ui->tableWidget;
    int currentRow = getRowPluginData(pluginName);
    auto widget = qobject_cast<PluginInfoWidget*>(table->cellWidget(currentRow,1));
    switch (command) {
        case PluginCommand::begin:{
            widget->setPluginJsonData(variant.value<PluginJsonData>());
            break;
        }
        case PluginCommand::end:{
            if(widget->is_status_normal()){
                table->removeRow(currentRow);
            }
            break;
        }
        case PluginCommand::log:
            break;
        case PluginCommand::progress:{
            widget->updateProgressValue(variant.toInt());
            break;
        }
        case PluginCommand::showpic:
            break;
        case PluginCommand::error:{
            widget->setPluginJsonErrorData(variant.value<PluginJsonErrorData>());
            break;
        }
        default:
            break;
    }
}

int MainWindow::getRowPluginData(const QString& pluginName)
{
    auto table = ui->tableWidget;
    int count = table->rowCount();
    PluginInfoWidget* widget{nullptr};
    int currentRow = 0;
    for(currentRow = 0;currentRow < count;currentRow++){
        if(table->item(currentRow,0)->text() == pluginName){
            widget = qobject_cast<PluginInfoWidget*>(table->cellWidget(currentRow,1));
            break;
        }
    }

    if(!widget){
        table->insertRow(currentRow);
        table->setRowHeight(currentRow,80);
        table->setItem(currentRow,0,new QTableWidgetItem(pluginName));
        table->setCellWidget(currentRow,1,new PluginInfoWidget);
    }
    return currentRow;
}
